﻿using Contracts;
using Entities;
using Entities.QueryPersist;
using Queries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace QueryExecutors
{
    public class QueryExecutor : IQueryExecutor
    {
        public QueryExecutor(IQueryStore queryPersist)
        {
            if (queryPersist == null)
            {
                throw new ArgumentNullException(nameof(queryPersist));
            }

            this.Query = queryPersist;
        }

        internal QueryExecutor()
        {

        }

        TQuery IQueryExecutor.Execute<TQuery>()
        {
            TQuery query = new TQuery();
            string queryExec = $"Query{query.GetType().Name}";  // Convention: "Query" + IQuery-type class name

            var queryInstance = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, queryExec);
            queryInstance.GetType()
                .GetMethod("Execute", BindingFlags.Public)
                .Invoke(this, new[] { query });

            return query;
        }

        protected IQueryStore Query;
    }
}
